package com.org.web.support.interceptors;

import com.org.platform.utils.CommonUtil;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author duheng
 * @Date 2021/5/29 17:43
 */
@Slf4j
@Component
public class ApiInterceptor implements HandlerInterceptor {

	public static final Map<String, String> tokenMap = new ConcurrentHashMap<>();

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uniShopToken = request.getHeader("token");
		String mobile = request.getHeader("mobile");
		log.info("mobile:{},reqToken:{}", mobile, uniShopToken);
		if (CommonUtil.isNullOrEmpty(uniShopToken) || CommonUtil.isNullOrEmpty(mobile)) {
			response.sendRedirect(request.getContextPath() + "/error/401");
			return false;
		}
		if (!stringRedisTemplate.hasKey(mobile)) {
			log.info("mobile:{} token expire", mobile);
			response.sendRedirect(request.getContextPath() + "/error/401");
			return false;
		}
		String tokenValue = stringRedisTemplate.opsForValue().get(mobile);
		if (!CommonUtil.equals(uniShopToken, tokenValue)) {
			response.sendRedirect(request.getContextPath() + "/error/401");
			return false;
		}
		return true;
		/*String token = request.getHeader("Authorization");
		if (!CommonUtil.isNullOrEmpty(token) && tokenMap.containsKey(token)) {
			return true;
		}
		response.sendRedirect(request.getContextPath() + "/error/401");*/
////		response.sendError(HttpStatusEnum.ERROR401.getCode(), HttpStatusEnum.ERROR401.getMessage());
//		response.setHeader("Access-Control-Allow-Origin", "*");
//		PrintWriter out = response.getWriter();
//		ResultModel resultModel = ResultModel.newFail(HttpStatusEnum.ERROR401.getCode(), HttpStatusEnum.ERROR401.getMessage());
//		out.print(JSONObject.toJSONString(resultModel));
//		out.flush();
//		return false;
	}
}
